<?php

namespace App\Http\Controllers\Home;

use App\Common\Logs\Logs;
use App\Common\Utill\Utills;
use App\Http\Controllers\Controller;
use App\Models\Articles;
use App\Models\Banners;
use App\Models\Category;
use App\Models\CategoryImport;
use App\Models\Websites;
use App\Models\WebsitesTopic;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class  IndexController extends Controller
{
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 首页
     * @return
     */
    public function index(Request $request)
    {

        $domain = $request->getHost(); // 获取域名
        if ($domain == 'zhanqun.pindarpr.com') {
            return redirect(route('admin.loginForm'));
        }
        exit();
        $indexActive = $request->input('indexActive', 1);
        $keywords = $request->input('keywords', '');
        //精选文章
        $choiseData = $this->choiseData();
        //轮播图
        $carouselData = $this->carouselData();
        //特色文章
        $featureArticle = $this->featureArticle();
        //栏目名称
        $websiteColumnData = $this->websiteColumnData;
        //网站信息
        $websiteData = $this->websiteData();
        if (!$websiteData) {
            return view("home.index.no_website");
        }
        //获取文件夹名称
        $folderStr = $this->folderStr;
        //热门文章
        $lastArticleData = $this->getLastArticleData(2);
        return view("home." . $folderStr . ".index")
            ->with('data', $choiseData)
            ->with('websiteData', $websiteData)
            ->with('indexActive', $indexActive)
            ->with('featureArticle', $featureArticle)
            ->with('keywords', $keywords)
            ->with('websiteColumnArr', $websiteColumnData)
            ->with('lastArticleData', $lastArticleData)
            ->with('carouselData', $carouselData);
    }

    /**
     * 精选文章
     * @return array|mixed[]
     */
    public function choiseData()
    {
        $data = Articles::query()
            ->select("id", "title", "content", "publish_time", 'thumbs as thumb', 'websites_topic_id', 'read_count')
            ->orderBy('id', 'desc')
            ->where('status', 2)
            ->where('is_del', 1)
            ->where('website_id', $this->websiteId)
            ->limit(6)
            ->get()
            ->toArray();
        foreach ($data as $key => $val) {
            $data[$key]['brief'] = mb_substr(strip_tags($val['content']), 0, 40, "UTF-8") . "...";
            $data[$key]['created_time'] = date("Y-m-d", strtotime($val['publish_time']));
            $data[$key]['publish_time'] = date("Y-m-d", strtotime($val['publish_time']));
            $data[$key]['topic_titles'] = DB::table("pd_websites_topic")->where("id", $val['websites_topic_id'])->value("titles");
        }
        return $data;
    }

    /**
     * 轮播图
     * @return mixed[]
     */
    public function carouselData()
    {
        $carouselData = Banners::query()
            ->where('website_id', $this->websiteId)
            ->where('status', 1)
            ->where('is_del', 1)
            ->select("id", "thumbs")
            ->orderBy('sort', 'asc')
            ->orderBy('id', 'asc')
            ->get()
            ->toArray();
        return $carouselData;
    }

    /**
     * 获取特色文章
     * @return
     */
    public function featureArticle()
    {
        $featureArticle = Articles::query()
            ->where('status', 2)
            ->where('is_del', 1)
            ->where('website_id', $this->websiteId)
            ->inRandomOrder()
            ->first();
        if ($featureArticle) {
            $featureArticle['topic_titles'] = DB::table("pd_websites_topic")->where("id", $featureArticle['websites_topic_id'])->value("titles");
            $featureArticle['created_time'] = date("Y-m-d", strtotime($featureArticle['created_at']));
            $featureArticle['brief'] = mb_substr(strip_tags($featureArticle['content']), 0, 90, "UTF-8") . "...";
        }
        return $featureArticle;
    }

    /**
     * 网站信息
     * @return
     */
    public function websiteData()
    {
        //网站信息
        $websiteData = Websites::query()
            ->where('id', $this->websiteId)
            ->select('id', 'names', 'titles', 'keywords', 'description', 'image_logo', 'emails', 'phones', 'address', 'about_us')
            ->first();
        if (!$websiteData) {
            return [];
        }
        return $websiteData;
    }

    /**
     * 文章列表页面
     */
    public function article_list(Request $request)
    {
        exit();
        $indexActive = $request->input('indexActive', 1);
        $topicId = $request->input('topicId', 0);
        $keywords = $request->input('keywords', '');
        //网站信息
        $websiteData = $this->websiteData();
        //获取文件夹名称
        $folderStr = $this->folderStr;
        $hotArticlefolder = $this->hotArticlefolder();
        if (in_array($folderStr, $hotArticlefolder)) {
            //热门文章
            $lastArticleData = $this->getLastArticleData(2);
        } else {
            //最新文章
            $lastArticleData = $this->getLastArticleData();
        }
        $topicInfo = [];
        if ($folderStr == 'index2') {
            //获取栏目信息
            $topicInfo = WebsitesTopic::query()->where("id", $topicId)->select("id", "titles")->first();
        }
        return view("home." . $folderStr . ".list")
            ->with('indexActive', $indexActive)
            ->with('websiteData', $websiteData)
            ->with('topicId', $topicId)
            ->with('topicInfo', $topicInfo)
            ->with('keywords', $keywords)
            ->with('websiteColumnArr', $this->websiteColumnData)
            ->with('lastArticleData', $lastArticleData);
    }

    /**
     * 文章数据
     */
    public function getLastArticleData($type = 1,$limitNum=10)
    {
        $query = Articles::query();
        if ($type == 2) {//热门文章
            $query->orderBy('read_count', 'desc');
        }
        $query->orderBy('id', 'desc');
        $lastArticleData = $query
            ->select("id", "title", "publish_time", 'read_count','thumbs')
            ->where('website_id', $this->websiteId)
            ->where('status', 2)
            ->where('is_del', 1)
            ->limit($limitNum)
            ->get()
            ->toArray();
        if ($lastArticleData) {
            foreach ($lastArticleData as $key => $val) {
                $lastArticleData[$key]['publish_time'] = date("Y-m-d", strtotime($val['publish_time']));
            }
        }
        return $lastArticleData;
    }

    /**
     * 文章列表页面数据
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function listData(Request $request)
    {
        $query = Articles::query();
        $page = $request->input("page", 1);
        $pageSize = $request->input('pageSize', 10);
        $articleTitle = $request->input('article_title', '');
        $topicId = $request->input('topicId', 0);
        $indexActive = $request->input('indexActive', 1);
        $query->where("website_id", $this->websiteId);
        if ($articleTitle) {
            $query->where('title', 'like', "%{$articleTitle}%");
            $topicId = 0;
        }
        if ($topicId) {
            $query->where('websites_topic_id', $topicId);
        }
        //列表数据
        $articleData = $query
            ->where('status', 2)
            ->where('is_del', 1)
            ->select("id", "title", "content", "publish_time", 'thumbs as thumb', 'websites_topic_id', 'read_count')
            ->orderBy('id', 'desc')
            ->paginate($pageSize, [], 'page', $page)
            ->toArray();
        $data = $articleData['data'];
        if ($data) {
            foreach ($data as $key => $val) {
                $data[$key]['brief'] = mb_substr(strip_tags($val['content']), 0, 80, "UTF-8") . "...";
                $data[$key]['publish_time'] = date("Y-m-d", strtotime($val['publish_time']));
                $data[$key]['url'] = '/home/article/info?id=' . $val['id'] . "&indexActive=" . $indexActive;
                $data[$key]['topicTitle'] = WebsitesTopic::query()->where("id", $val['websites_topic_id'])->value("titles");
            }
        }
        $result['code'] = 0;
        $result['total'] = $articleData['total'];
        $result['data'] = $data;
        return Utills::resultData($result);
    }

    /**
     * 文章详情页面
     * @param Request $request
     */
    public function info(Request $request)
    {
        exit();
        $id = $request->input('id', '');
        $keywords = $request->input('keywords', '');
        //获取文件夹名称
        $folderStr = $this->folderStr;
        if($folderStr == "index3" && !$id){
            $id = Articles::query()->where("website_id",$this->websiteId)->orderBy("id",'desc')->value('id') ?? 0;
        }
        //详情
        $info = Articles::query()->where('id', $id)->first();
        $info['thumb'] = $info['thumbs'];
        $info['publish_time'] = date("Y-m-d", strtotime($info['publish_time']));
        $info['topicTitle'] = WebsitesTopic::query()->where("id", $info['websites_topic_id'])->value("titles") ?? "";
        $hotArticlefolder = $this->hotArticlefolder();
        if (in_array($folderStr, $hotArticlefolder)) {
            $limitNum= $this->hotArticlefolderNum($folderStr);
            //热门文章
            $lastArticleData = $this->getLastArticleData(2,$limitNum);
        } else {
            //最新文章
            $lastArticleData = $this->getLastArticleData();
        }
        //上一篇文章
        $previousData = $this->preNextArticleData(1, $id, $info['websites_topic_id']);
        if (!$previousData) {
            $previousData = $info;
        }
        //下一篇文章
        $nextData = $this->preNextArticleData(2, $id, $info['websites_topic_id']);
        if (!$nextData) {
            $nextData = $info;
        }
        $indexActive = $request->input('indexActive', 1);
        //网站信息
        $websiteData = $this->websiteData();
        //阅读数加1
        Articles::query()->where("id", $id)->increment('read_count');
        //相关文章
        $relationArticle = $this->relationArticle($id,$info['websites_topic_id']);

        return view('home.' . $folderStr . '.info')
            ->with('info', $info)
            ->with('lastArticleData', $lastArticleData)
            ->with('previousData', $previousData)
            ->with('websiteData', $websiteData)
            ->with('indexActive', $indexActive)
            ->with('keywords', $keywords)
            ->with('relationArticle', $relationArticle)
            ->with('websiteColumnArr', $this->websiteColumnData)
            ->with('nextData', $nextData);
    }

    /**
     * 获取热门文章的文件夹
     * @return string[]
     */
    public function hotArticlefolder()
    {
        $result = ["index2","index3"];
        return $result;
    }

    /**
     * 热门文章 展示数量
     * @param $folder
     * @return void
     */
    public function hotArticlefolderNum($folder="")
    {
        switch ($folder) {
            case "index3":
                $limitNum = 3;
                break;
            default:
                $limitNum = 10;
        }
        return $limitNum;
    }

    /**
     * 相关文章
     * @param $id
     * @param $topicId
     * @return
     */
    public function relationArticle($id,$topicId,$limitNum=4)
    {
        $data = Articles::query()
            ->where('status', 2)
            ->where('is_del', 1)
            ->where('id','<>',$id)
            ->where('website_id', $this->websiteId)
            ->select("id", "title", "content", "publish_time", 'thumbs as thumb', 'websites_topic_id', 'read_count')
            ->inRandomOrder()
            ->limit($limitNum)
            ->get()->toArray();
        if ($data) {
            foreach ($data as $key => $val) {
                $data[$key]['brief'] = mb_substr(strip_tags($val['content']), 0, 40, "UTF-8") . "...";
                $data[$key]['publish_time'] = date("Y-m-d", strtotime($val['publish_time']));
                $data[$key]['topic_titles'] = DB::table("pd_websites_topic")->where("id", $val['websites_topic_id'])->value("titles");
            }
        }
        return $data;
    }

    /**
     * 上一篇文章 / 下一篇文章
     * @return void
     */
    /**
     * @param $type
     * @param $id
     * @param $topicId
     * @return []
     */
    public function preNextArticleData($type, $id, $topicId)
    {
        $query = Articles::query();
        if ($type == 1) {//上一篇
            $query->where('id', '<', $id);
        } else {//下一篇
            $query->where('id', '>', $id);
        }
        $data = $query->where('websites_topic_id', $topicId)
            ->orderBy('id', 'desc')
            ->select('id', 'title')
            ->first();
        return $data;
    }


    /**
     * 获取图片
     * @param $str
     * @param bool $default
     * @return bool|mixed
     */
    public function getImg($str, $default = false)
    {
        if (!$default) {
            $pattern = "/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png|\.jpeg]))[\'|\"].*?[\/]?>/i";
            preg_match($pattern, $str, $array);
            if (isset($array[1])) {
                return $array[1];
            }
            return "https://qinipic.pindarpr.com/soft_article/pic/0e6b002d-e35f-4be7-9b13-8d5d8d4dea08.jpg";
        } else {
            return $default;
        }
    }

    public function categoryCopy(Request $request)
    {
//        $websiteId = $request->input("websiteId");
//        if(!$websiteId){
//            echo "网站id不能为空";exit();
//        }
        exit();
        $data = CategoryImport::query()->select("id","category_name")->get()->toArray();
        for ($i=145;$i<= 162;$i++){
            echo "正在生成分类:".$i.PHP_EOL;
            $newData = array();
            foreach ($data as $kk=>$vv){
                $newData[$kk]['admin_id'] = 1;
                $newData[$kk]['website_id'] = $i;
                $newData[$kk]['category_name'] = $vv['category_name'];
                $newData[$kk]['type'] = 1;
                $newData[$kk]['use_numbers'] = 0;
                $newData[$kk]['weights'] = 1;
                $newData[$kk]['created_at'] = date("Y-m-d H:i:s");
            }
            DB::table("pd_category")->insert($newData);
        }

        echo "文章分类 success-".date("Y-m-d H:i:s").PHP_EOL;
    }

    public function website(Request $request)
    {
        $styleId = $request->input("styleId");
        if(!$styleId){
            echo "风格id不能为空";exit();
        }
        $websiteData = Websites::query()->orderBy("id","desc")->first()->toArray();
        $websiteData['created_at'] = date("Y-m-d H:i:s");
        unset($websiteData['id']);
        unset($websiteData['updated_at']);
        $id = DB::table("pd_websites")->insertGetId($websiteData);
        $postData['website_id'] = $id;
        $postData['websites_style_id'] = $styleId;
        $postData['admin_id'] = 1;
        $postData['created_at'] = date("Y-m-d H:i:s");
        DB::table("pd_websites_admin")->insert($postData);
        $created_at = date("Y-m-d H:i:s");
        $topicArr = array(
            array("website_id"=>$id,"titles"=>'最新资讯','sort'=>1,'created_at'=>$created_at),
            array("website_id"=>$id,"titles"=>'行业文章','sort'=>2,'created_at'=>$created_at),
            array("website_id"=>$id,"titles"=>'市场快讯','sort'=>3,'created_at'=>$created_at)
        );
        DB::table("pd_websites_topic")->insert($topicArr);
        sleep(2);
        //添加任务
        $query = WebsitesTopic::query();
        $data = $query
            ->where("website_id",$id)
            ->where("is_del",1)
            ->where('status',1)
            ->select("id",'website_id')
            ->get()
            ->toArray();
        if($data){
            $postData =[];
            foreach ($data as $key=>$val){
                $postData[$key]['websites_id'] = $val['website_id'];
                $postData[$key]['websites_topic_id'] = $val['id'];
                $postData[$key]['plan_time'] = time();
                $postData[$key]['plan_numbers'] = 2;
                $postData[$key]['admin_id'] = 1;
                $postData[$key]['operation_id'] = 1;
                $postData[$key]['created_at'] = date("Y-m-d H:i:s");
            }
            $res = DB::table("pd_tasks")->insert($postData);
            if(!$res){
                Logs::crontabLog("添加失败",$postData,"task_add");
            }
            //Logs::crontabLog("添加成功",$postData,"task_add");
            echo "success:".date("Y-m-d H:i:s");
        }


        echo "网站信息 success-".date("Y-m-d H:i:s").PHP_EOL;
    }


    public function websiteDomain()
    {
        $domainData = Websites::query()->get()->toArray();
        $domainStr = "";
        foreach ($domainData as $val){
            $domainStr.="网站id:".$val['id'].",网站域名:".$val['domains'].",地址:<a href='http://".$val['domains']."' target='_blank'>".$val['names']."</a><hr>";
        }
        echo  $domainStr;
        echo "success：".date("Y-m-d H:i:s").PHP_EOL;
    }

    // 新增队列数据
    public function addQueue()
    {
        $redis = Utills::redisObj();
        for ($i=1;$i<=100;$i++){
            $redis->rPush('test-queue', $i);
        }
        echo 'success'.date("Y-m-d H:i:s");
    }

}
